import { useState, useEffect, useRef } from 'react';
import styles from './index.less';
import { Tabs, Button, message, TimePicker } from 'antd';
import { connect } from 'umi';
import moment from 'moment';

import { TRAlert, TRDefault, TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { downloadHandle } from '#/utils/utils';
import { deleteIcon, plus, exportIcon, lock } from '@/assets';
import {
  TradeStrategy,
  SubmitType,
  TradeStrategyMap,
} from '@/pages/Tianji/TenDaysCentralizedBidding/constant';
import {
  tenDaysTradeSubmit,
  cancelTimelySubmit,
  deleteProgram,
  exportProgram,
} from '@/pages/Tianji/TenDaysCentralizedBidding/services';
import { exportMoreSheet } from '@/utils/fileExport.js';

import ProgramSetting from '../ProgramSetting';
import SubmitStatusModal from '../SubmitStatusModal';
import SearchStatusModal from '../SearchStatusModal';
import PriceValidationModal from '../PriceValidationModal';
import PowerValidationModal from '../PowerValidationModal';
import ImportBtn from '../ImportBtn';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { getDefaultProgramId, exportColumns } from '../../helper';

const { TabPane } = Tabs;

// 在这个组件中保存、申报、定时申报方案
const Main = ({
  username,
  menuCode,
  buttonPermissions,
  initProgramInfo,
  tradeCenterTime,
  currentProgramId,
  currentProgramInfo,
  unitInfo,
  programList,
  tradeSeqId,
  hasModified,
  tradeSeqInfo,
  selectedUnitIds,
  dispatch,
  market,
  stations,
  stationCapacityInfo,
  maxValue,
  formData,
}) => {
  const is_SD = market.value === 'PHBSD';
  const importKey = 'jiZhongJingJiaFangAnDingShiShenBao';
  const submitStatusRef = useRef();
  const SearchStatusRef = useRef();
  const priceValidationModalRef = useRef();
  const powerValidationModalRef = useRef();

  const initSelectedUnitInfo = {
    unitList: [], // 已选择的交易单元的限额信息列表
    buyLimitAll: [], // 已选择的交易单元的买入限额总和列表
    sellLimitAll: [], // 已选择的交易单元的卖出限额总和列表
  };

  const [state, setState] = useState({
    canImport: buttonPermissions.some((item) => item.menuCode === importKey),
  });

  const initTimer = {
    format: 'HH:mm',
    value: null,
    lock: false,
    timerComVisible: false,
  };

  const [timer, setTimer] = useState(initTimer),
    // 已选择的交易单元的信息
    [selectedUnitInfo, setSelectedUnitInfo] = useState(initSelectedUnitInfo),
    [priceValidationList, setPriceValidationList] = useState({}),
    [powerValidationList, setPowerValidationList] = useState([]); // [{hourOrder: 1, tradeStrategy: 0, unitList: ['大山台一二期', '大山台三期']}]

  // 切换交易方案 => 方案对应的交易单元 => 修改已选择交易单元id
  // 不能监听交易方案的改变，因为交易方案的改变触发因素极多，同理不能监听方案对应的交易单元；需要监听方案对应的交易单元转换为的字符串
  useEffect(() => {
    selectedUnitIdsFunc();
  }, [JSON.stringify(currentProgramInfo.unitList)]);

  // 选择的交易单元改变 => 获取所选交易单元限额限价等信息
  useEffect(() => {
    selectedUnitInfoFunc();
  }, [selectedUnitIds, unitInfo]);

  // 选择的交易单元改变 => 获取所选交易单元限额限价等信息 => 将限额信息在方案中进行展示
  useEffect(() => {
    addLimitInfo();
  }, [selectedUnitInfo]);

  // 方案id发生改变 => 更新方案定时相关数据
  useEffect(() => {
    fetchTimer();
  }, [currentProgramInfo?.programInfo?.id]);

  useEffect(() => {
    if (
      currentProgramInfo.editPermission &&
      currentProgramInfo.programInfo.status === 1 &&
      currentProgramInfo.programInfo.timelySubmitTime
    ) {
      let obj = {
        ...timer,
        lock: true,
        value: moment(currentProgramInfo.programInfo.timelySubmitTime),
      };
      setTimer(obj);
    } else {
      setTimer(initTimer);
    }
  }, [JSON.stringify(currentProgramInfo.programInfo)]);

  const selectedUnitIdsFunc = () => {
    dispatch({
      type: 'tenDaysCentralizedBidding/setSelectedUnitIds',
      payload: [],
    });
    if (!currentProgramInfo?.unitList?.length) return;
    dispatch({
      type: 'tenDaysCentralizedBidding/setSelectedUnitIds',
      payload: currentProgramInfo.unitList.map((item) => item.id + ''),
    });
  };

  const cancelTimelySubmitFunc = async () => {
    dispatch({
      type: 'tenDaysCentralizedBidding/setAddLoadingNum',
    });
    const res = await cancelTimelySubmit(currentProgramId);
    dispatch({
      type: 'tenDaysCentralizedBidding/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      // setTimer(initTimer);
      TRMessage.success('取消定时成功');
      dispatch({
        type: 'tenDaysCentralizedBidding/fetchHourOrderInfoEffect',
        payload: currentProgramId,
      });
    } else {
      TRMessage.error(res?.message || '取消定时失败');
      if (res?.statusCode === '410') {
        updateProgramList();
      }
    }
  };

  // 收集已选择的交易单元的信息
  const selectedUnitInfoFunc = () => {
    setSelectedUnitInfo(initSelectedUnitInfo);
    // 如果无编辑权限，则说明场站未覆盖到，则只展示方案返回的限额即可
    if (!currentProgramInfo.editPermission) {
      return;
    }
    if (!selectedUnitIds.length || !Object.keys(unitInfo).length) return;
    let unitList = [],
      buyLimitAll = [],
      sellLimitAll = [];
    if (!is_SD) {
      selectedUnitIds.forEach((id) => {
        unitInfo[id] ? unitList.push(unitInfo[id]) : '';
      });
      for (let i = 1; i <= 24; i++) {
        let buyLimit = 0,
          sellLimit = 0;
        unitList.forEach((item) => {
          buyLimit = Math.round((buyLimit + item.limitMapping[i].unitBuyLimit) * 1000) / 1000;
          sellLimit = Math.round((sellLimit + item.limitMapping[i].unitSellLimit) * 1000) / 1000;
        });
        buyLimitAll.push(buyLimit);
        sellLimitAll.push(sellLimit);
      }
    } else {
      //山东不区分场站 交易限额
      const _unitInfo = Object.values(unitInfo);
      if (!_unitInfo.length) return;
      let maxValue = 0;
      stations.forEach((t) => {
        if (selectedUnitIds.includes(t.value)) {
          if (stationCapacityInfo?.[t.value] > maxValue) {
            maxValue = stationCapacityInfo?.[t.value];
          }
          unitList.push({
            id: t.value,
            stationTitle: t.label,
          });
        }
      });
      dispatch({
        type: 'tenDaysCentralizedBidding/setMaxValue',
        payload: maxValue * 24,
      });
    }

    setSelectedUnitInfo({
      unitList,
      buyLimitAll,
      sellLimitAll,
    });
  };

  const addLimitInfo = () => {
    if (!selectedUnitInfo.unitList.length) return;
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList.forEach((item, index) => {
      item.buyLimit = selectedUnitInfo.buyLimitAll[index];
      item.sellLimit = selectedUnitInfo.sellLimitAll[index];
      //山东所选场站装机容量上限
      if (is_SD && item.firstSubmitPower > maxValue) {
        item.firstSubmitPower = maxValue;
      }
    });

    dispatch({
      type: 'tenDaysCentralizedBidding/setCurrentProgramInfo',
      payload: data,
    });
  };

  // 设置定时申报时间及是否锁定
  const changeTimer = (lock, time) => {
    if (lock) {
      // 设置定时申报
      let obj = {
        ...timer,
        timerComVisible: false,
      };
      setTimer(obj);
      submitProgram(1, time);
    } else {
      // 取消定时申报
      cancelTimelySubmitFunc();
    }
  };

  // 设置、取消定时申报弹框的显示
  const handleTimer = async () => {
    if (
      !buttonPermissions.filter((item) => item.menuCode === 'jiZhongJingJiaFangAnDingShiShenBao')
        .length
    ) {
      return TRMessage.info('请联系管理员获取相关权限');
    }

    if (timer.lock) {
      let obj = await TRAlert.eamDelete('是否取消当前定时申报');
      if (obj.index === 1) {
        changeTimer(false);
      }
    } else {
      let data = JSON.parse(JSON.stringify(timer));
      data.timerComVisible = true;
      setTimer(data);
    }
  };

  const hideTimerCom = () => {
    let data = JSON.parse(JSON.stringify(timer));
    if (data.timerComVisible) {
      data.timerComVisible = false;
      setTimer(data);
    }
  };

  // 新增方案
  const addProgram = () => {
    if (programList.length && programList[programList.length - 1].id === '-1') {
      TRMessage.warning('同时只能新增一个方案');
      return;
    }

    // 确定方案名；遍历方案列表，如果有[当前用户名+数字]的方案，则获取最大数字，新增方案名为[当前用户名+最大数字加1]；如果没有[当前用户名+数字]的方案，新增方案名为[当前用户名+1]
    let programListData = JSON.parse(JSON.stringify(programList));
    let maxNum = 0;
    programListData.forEach((item) => {
      let reg = new RegExp(`^${username}\\d+$`);
      if (reg.test(item.title)) {
        let regNum = new RegExp(`^${username}(\\d+)$`);
        let num = item.title.match(regNum)[1];
        if (parseInt(num) > parseInt(maxNum)) maxNum = num;
      }
    });

    programListData.push({
      id: '-1',
      title: username + ++maxNum,
      deletePermission: true,
      status: 0,
    });

    dispatch({
      type: 'tenDaysCentralizedBidding/setProgramList',
      payload: programListData,
    });
    // 选中当前新增方案
    changeCurrentProgramId('-1');

    dispatch({
      type: 'tenDaysCentralizedBidding/setHasModified',
      payload: true,
    });
  };

  // 买入卖出时，段一段二价格校验
  const priceValidation = () => {
    setPriceValidationList([]);
    let data = {
      buy: [],
      sell: [],
    };
    currentProgramInfo.hourOrderInfoList.forEach((item) => {
      // 卖出；卖出时，段二价格 >= 段一价格
      if (item.tradeStrategy === TradeStrategy.SELL && item.secondPrice < item.firstPrice) {
        data.sell.push(item.hourOrder);
      }
      // 买入；买入时，段二价格 <= 段一价格
      if (item.tradeStrategy === TradeStrategy.BUY && item.secondPrice > item.firstPrice) {
        data.buy.push(item.hourOrder);
      }
    });
    if (data.buy.length || data.sell.length) {
      setPriceValidationList(data);
      priceValidationModalRef.current.initHandle();
      return false;
    }
    return true;
  };

  // 是否有超出限额的场站校验
  const powerValidation = () => {
    setPowerValidationList([]);
    // 如果选择了接受限额调剂，则不进行校验，返回true
    if (currentProgramInfo.programInfo.adjust) return true;
    // 遍历方案的24个时点；（tradeStrategy为0-卖出 || 1-买入） && （submitType为0-固定值 || 1-装机容量）时需要进行校验；
    let data = [];
    currentProgramInfo.hourOrderInfoList.forEach((item) => {
      if (item.tradeStrategy !== TradeStrategy.SELL && item.tradeStrategy !== TradeStrategy.BUY)
        return;
      if (item.submitType !== SubmitType.FIXED && item.submitType !== SubmitType.INSTALLED_CAPACITY)
        return;
      let obj = {
        hourOrder: item.hourOrder,
        tradeStrategy: item.tradeStrategy,
        unitList: [],
      };
      if (item.tradeStrategy === TradeStrategy.SELL) {
        selectedUnitIds.forEach((unitId) => {
          let currentUnitInfo = unitInfo[unitId];
          if (item.submitType === SubmitType.FIXED) {
            if (
              item.firstSubmitPower * 2 >
              currentUnitInfo.limitMapping[item.hourOrder].unitSellLimit
            ) {
              obj.unitList.push(currentUnitInfo.stationTitle);
            }
          }
          if (item.submitType === SubmitType.INSTALLED_CAPACITY) {
            if (
              item.firstSubmitPower *
                2 *
                currentUnitInfo.limitMapping[item.hourOrder].unitCapacity >
              currentUnitInfo.limitMapping[item.hourOrder].unitSellLimit
            ) {
              obj.unitList.push(currentUnitInfo.stationTitle);
            }
          }
        });
      }
      if (item.tradeStrategy === TradeStrategy.BUY) {
        selectedUnitIds.forEach((unitId) => {
          let currentUnitInfo = unitInfo[unitId];
          if (item.submitType === SubmitType.FIXED) {
            if (
              item.firstSubmitPower * 2 >
              currentUnitInfo.limitMapping[item.hourOrder].unitBuyLimit
            ) {
              obj.unitList.push(currentUnitInfo.stationTitle);
            }
          }
          if (item.submitType === SubmitType.INSTALLED_CAPACITY) {
            if (
              item.firstSubmitPower *
                2 *
                currentUnitInfo.limitMapping[item.hourOrder].unitCapacity >
              currentUnitInfo.limitMapping[item.hourOrder].unitBuyLimit
            ) {
              obj.unitList.push(currentUnitInfo.stationTitle);
            }
          }
        });
      }

      if (obj.unitList.length) {
        data.push(obj);
      }
    });
    if (data.length) {
      setPowerValidationList(data);
      powerValidationModalRef.current.initHandle();
      return false;
    }
    return true;
  };

  // 保存、定时申报、立即申报方案 0:保存,1:定时申报,2:立即申报
  const submitProgram = async (type, time) => {
    // 按钮权限判断
    switch (type) {
      case 0:
        if (
          !buttonPermissions.filter((item) => item.menuCode === 'jiZhongJingJiaFangAnBaoCun').length
        ) {
          return TRMessage.info('请联系管理员获取相关权限');
        }
        break;
      case 1:
        // 定时申报按钮权限判断放在了handleTimer函数中
        break;
      case 2:
        if (
          !buttonPermissions.filter((item) => item.menuCode === 'jiZhongJingJiaFangAnLiJiShenBao')
            .length
        ) {
          return TRMessage.info('请联系管理员获取相关权限');
        }
        break;
    }
    // 交易单元不能为空
    if (!selectedUnitInfo.unitList.length) {
      message.warning('请选择交易单元');
      return;
    }
    // 买入卖出时，段一段二价格校验
    if (!priceValidation()) return;
    // 是否有超出限额的场站校验
    if (!powerValidation()) return;
    if (type === 2) {
      // 验证交易时间
      if (moment(tradeCenterTime).isBefore(tradeSeqInfo.submitStartTime)) {
        TRMessage.error('选择交易日申报时间未开始，请在交易申报时间范围进行申报');
        return;
      } else if (
        moment(tradeCenterTime).isAfter(moment(tradeSeqInfo.submitEndTime).subtract(8, 'm'))
      ) {
        TRMessage.error(
          '选择交易日申报时间应早于申报结束时间前8分钟，请在交易申报时间范围进行申报',
        );
        return;
      }
    }
    let hasEmpty = false;
    let hourOrderInfoList = JSON.parse(JSON.stringify(currentProgramInfo.hourOrderInfoList));
    hourOrderInfoList.forEach((item) => {
      if (is_SD) {
        if (item.tradeStrategy === undefined) {
          hasEmpty = true;
          return;
        }
        item.date = item.hourOrder;
        item.hourOrder = 0;
        item.buyLimit = 0;
        item.sellLimit = 0;
        item.secondSubmitPower = 0;
        item.totalPower = 0;
        return;
      }
      item.secondSubmitPower = item.firstSubmitPower;
      item.totalPower = item.firstSubmitPower * 2;
    });
    //交易方向必填
    if (hasEmpty) {
      TRMessage.error('交易方向不能为空');
      return;
    }

    let data = {
      adjust: currentProgramInfo.programInfo.adjust,
      intervals: hourOrderInfoList,
      operateType: type, // 0:保存,1:定时申报,2:立即申报
      programTitle: programList.filter((item) => item.id == currentProgramId)[0].title,
      marketId: market.value,
      sequenceId: !is_SD ? tradeSeqId : market.value + tradeSeqId,
      unitDtoList: selectedUnitInfo.unitList.map((item) => {
        return {
          id: item.id,
          title: item.stationTitle,
        };
      }),
    };
    // 修改方案
    if (currentProgramId !== '-1') {
      data.programId = currentProgramId;
      data.intervals.forEach((item) => {
        item.programId = currentProgramId;
      });
      data.unitDtoList.forEach((item) => {
        item.programId = currentProgramId;
      });
    }
    // 定时申报
    if (type === 1) {
      data.timelySubmitTime = formData.date + ' ' + time.format('HH:mm:ss');
    }
    dispatch({
      type: 'tenDaysCentralizedBidding/setAddLoadingNum',
    });
    const res = await tenDaysTradeSubmit(menuCode, data);
    dispatch({
      type: 'tenDaysCentralizedBidding/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      await dispatch({
        type: 'tenDaysCentralizedBidding/fetchProgramsEffect',
      });
      dispatch({
        type: 'tenDaysCentralizedBidding/fetchHourOrderInfoEffect',
        payload: res.data.id,
      });
      // 根据返回的方案id，选中当前的方案
      dispatch({
        type: 'tenDaysCentralizedBidding/setCurrentProgramId',
        payload: res.data.id,
      });
      let msg;
      switch (type) {
        case 0:
          msg = '保存方案成功';
          break;
        case 1:
          msg = '定时申报成功';
          break;
        case 2:
          msg = '立即申报成功';
          // TRAlert.Info(`预计${moment(tradeCenterTime).add(parseInt(res.data.predictWaitMinutes), 'm').format('YYYY-MM-DD HH:mm:ss')}前完成方案全部申报工作，请知悉。您可在“方案总览”功能中查看各个交易单元最新申报结果。`);
          break;
      }
      TRMessage.success(msg);
    } else {
      let msg = res?.message;
      if (!msg) {
        switch (type) {
          case 0:
            msg = '保存方案失败';
            break;
          case 1:
            msg = '定时申报失败';
            break;
          case 2:
            msg = '立即申报失败';
            break;
        }
      }
      TRMessage.error(msg);
      if (res?.statusCode === '410') {
        updateProgramList();
      }
      setTimer(initTimer);
    }
  };

  const fetchTimer = () => {
    setTimer(initTimer);
    if (!currentProgramInfo?.programInfo?.id) return;
    if (currentProgramInfo.programInfo.lock) {
      setTimer({
        ...initTimer,
        lock: true,
        value: moment(currentProgramInfo.programInfo.timelySubmitTime),
      });
    }
  };

  const changeCurrentProgramId = async (id) => {
    if (id === currentProgramId) return;
    if (hasModified) {
      let obj = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
      if (obj.index === 0) return;
    }

    // 如果切换到的方案不是新增方案，则把方案列表中id为'-1'的新增方案删除掉
    if (id !== '-1') {
      let programListData = programList.filter((item) => {
        return item.id !== '-1';
      });
      dispatch({
        type: 'tenDaysCentralizedBidding/setProgramList',
        payload: programListData,
      });
    }

    // 初始化方案数据
    dispatch({
      type: 'tenDaysCentralizedBidding/setSelectedRowKeys',
      payload: [],
    });

    dispatch({
      type: 'tenDaysCentralizedBidding/setCurrentProgramId',
      payload: id,
    });
    dispatch({
      type: 'tenDaysCentralizedBidding/fetchHourOrderInfoEffect',
      payload: id,
    });
  };

  const deleteProgramFunc = async (id, e) => {
    e.stopPropagation();

    if (hasModified && id === currentProgramId) {
      let objM = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
      if (objM.index === 0) return;
      dispatch({
        type: 'tenDaysCentralizedBidding/setHasModified',
        payload: false,
      });
    }

    let obj = await TRAlert.eamDelete('是否确认删除');
    if (obj.index === 0) return;
    // 如果是新增方案，则直接删除方案列表中的方案，并重新获取默认选中方案
    if (id === '-1') {
      let programListData = programList.filter((item) => {
        return item.id !== '-1';
      });
      TRMessage.success('删除方案成功');
      dispatch({
        type: 'tenDaysCentralizedBidding/setProgramList',
        payload: programListData,
      });

      if (!programListData.length) {
        dispatch({
          type: 'tenDaysCentralizedBidding/setSelectedUnitIds',
          payload: [],
        });
        setSelectedUnitInfo(initSelectedUnitInfo);
        dispatch({
          type: 'tenDaysCentralizedBidding/setCurrentProgramInfo',
          payload: initProgramInfo,
        });
        return;
      }

      let defaultProgramId = null;
      if (programListData.length) {
        defaultProgramId = getDefaultProgramId(programListData, username);
      }

      dispatch({
        type: 'tenDaysCentralizedBidding/setCurrentProgramId',
        payload: defaultProgramId,
      });
      dispatch({
        type: 'tenDaysCentralizedBidding/fetchHourOrderInfoEffect',
        payload: defaultProgramId,
      });
    } else {
      // 如果非新增方案，则调用删除接口
      deleteProgramAsync(id);
    }
  };

  // 调用删除接口
  const deleteProgramAsync = async (id) => {
    dispatch({
      type: 'tenDaysCentralizedBidding/setAddLoadingNum',
    });
    const res = await deleteProgram(menuCode, id);
    dispatch({
      type: 'tenDaysCentralizedBidding/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      // 如果删除方案为当前选中方案，则重新获取方案列表，并重新设置默认选中方案
      // 如果删除方案非当前选中方案，则重新获取方案列表即可
      if (id === currentProgramId) {
        updateProgramList();
      } else {
        dispatch({
          type: 'tenDaysCentralizedBidding/fetchProgramsEffect',
        });
      }
      TRMessage.success('删除方案成功');
    } else {
      if (res?.statusCode === '410') {
        if (id === currentProgramId) {
          updateProgramList();
        } else {
          dispatch({
            type: 'tenDaysCentralizedBidding/fetchProgramsEffect',
          });
        }
      }
      TRMessage.error(res?.message || '删除方案失败');
    }
  };

  // 导出方案
  const exportProgramAsync = async () => {
    // 新建方案无法导出方案
    if (currentProgramId === '-1') {
      return TRMessage.info('新建方案无法进行导出操作，请保存后再导出');
    }
    if (
      !buttonPermissions.filter((item) => item.menuCode === 'jiZhongJingJiaFangAnDaoChu').length
    ) {
      return TRMessage.info('请联系管理员获取相关权限');
    }
    if (!is_SD) {
      const fileName = tradeSeqInfo.sequenceTitle + currentProgramInfo.programInfo.title;
      const stationName = selectedUnitInfo.unitList.map((t) => t.stationTitle).join('、');
      let sheets = [
        {
          columns: exportColumns,
          title: tradeSeqInfo.sequenceTitle + '-' + currentProgramInfo.programInfo.title,
          data: [],
          myMerges: [],
          mergeIndex: [1, 2, 3, 4, 5, 6, 7, 8, 9],
          insertTop: [['交易单元', stationName]],
        },
      ];
      currentProgramInfo.hourOrderInfoList.map((item, index) => {
        const isFixed = item.submitType === SubmitType.FIXED;
        let obj = {
          ...item,
          tradeStrategy: TradeStrategyMap[item.tradeStrategy],
          upperPrice: item.upperPrice.toFixed(2),
          lowerPrice: item.lowerPrice.toFixed(2),
          submitType: isFixed ? '-' : '装机容量（MW·h）',
          firstSubmitPower: isFixed ? '-' : (item.firstSubmitPower * 100).toFixed(1),
          fixedValue: isFixed ? item.firstSubmitPower.toFixed(3) : '-',
          firstPrice: item.firstPrice.toFixed(2),
          totalPower: isFixed
            ? item.firstSubmitPower.toFixed(3)
            : `装机容量 * ${Math.round(item.firstSubmitPower * 100)}%`,
        };

        sheets[0].data.push(obj);
      });

      exportMoreSheet(sheets, fileName);
      return;
    }
    try {
      let data = await exportProgram(currentProgramId);
      if (data.data.type.includes('application/json')) {
        let reader = new FileReader();
        reader.onload = function () {
          let res = reader.result;
          let result = JSON.parse(res); // blob格式转成json
          if (result?.statusCode === '410') {
            // 对应业务逻辑
            TRMessage.error(res?.message || '方案已被删除，导出失败');
            updateProgramList();
          }
        };
        reader.readAsText(data.data);
      } else {
        if (data.data && data.data instanceof Blob) {
          const realFileName = data.response.headers
            .get('content-disposition')
            .split('filename=')[1];
          downloadHandle(data.data, decodeURI(realFileName));
        } else {
          TRMessage.error('导出失败');
        }
      }
    } catch (e) {
      TRMessage.error('导出失败');
    }
  };

  // 获取定时申报按钮状态，true表示禁用，false表示启用
  const getTimerBtnStatus = () => {
    return (
      !currentProgramInfo.editPermission ||
      currentProgramInfo.programInfo.status === 2 ||
      (currentProgramInfo.programInfo.status === 1 &&
        !currentProgramInfo.programInfo.timelySubmitTime)
    );
  };

  // 刷新方案列表
  const updateProgramList = () => {
    dispatch({
      type: 'tenDaysCentralizedBidding/fetchProgramsEffect',
      payload: {
        setDefaultProgramId: true,
      },
    });
    dispatch({
      type: 'tenDaysCentralizedBidding/setHasModified',
      payload: false,
    });
  };

  // 新增Program然后把读取的数据加进列表
  const addProgramAndSetListData = (obj) => {
    addProgram();
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: {
        deletePermission: true,
        editPermission: true,
        programInfo: {
          adjust: true,
        },
        hourOrderInfoList: obj.tableData,
      },
    });

    dispatch({
      type: 'tenDaysCentralizedBidding/setSelectedUnitIds',
      payload: obj.marketingUnit,
    });
  };

  return (
    <div className={`${styles.main} border-radius-5`}>
      <div className={styles.tabAndOperate}>
        <div className={styles.mainTab}>
          <Tabs
            activeKey={currentProgramId + ''}
            onChange={(id) => changeCurrentProgramId(id)}
            tabBarGutter={24}
          >
            {programList.map((item) => {
              return (
                <TabPane
                  tab={
                    <div className={styles.tabPane}>
                      <span>{item.title}</span>
                      {item.deletePermission && item.status === 0 ? (
                        <img
                          className={styles.deleteIcon}
                          src={deleteIcon}
                          onClick={(e) => deleteProgramFunc(item.id, e)}
                        />
                      ) : (
                        ''
                      )}
                    </div>
                  }
                  key={item.id}
                />
              );
            })}
          </Tabs>
          <div
            className={`${styles.plusBtn} ${programList.length ? '' : styles.marginLeft0}`}
            onClick={addProgram}
          >
            {/* <img className={styles.icon} src={plus} /> */}
            <PlusOutlined className={styles.icon} />
            <span>新增</span>
          </div>
        </div>
        {programList.length ? (
          <div className={styles.mainOperate}>
            {!is_SD ? (
              <Button
                onClick={() => {
                  submitStatusRef.current.initHandle();
                }}
              >
                挂单状态
              </Button>
            ) : (
              <Button
                onClick={() => {
                  SearchStatusRef.current.initHandle();
                }}
              >
                状态查询
              </Button>
            )}
            <Button
              onClick={() => {
                submitProgram(0);
              }}
              disabled={
                !currentProgramInfo.editPermission ||
                currentProgramInfo.programInfo.status === 1 ||
                currentProgramInfo.programInfo.status === 2
              }
            >
              保存
            </Button>
            <Button
              onClick={() => {
                submitProgram(2);
              }}
              disabled={
                !currentProgramInfo.editPermission ||
                currentProgramInfo.programInfo.status === 1 ||
                currentProgramInfo.programInfo.status === 2
              }
            >
              立即申报
            </Button>
            <Button
              className={styles.timerBtn}
              type={getTimerBtnStatus() ? 'default' : 'primary'}
              onClick={handleTimer}
              onBlur={hideTimerCom}
              disabled={getTimerBtnStatus()}
            >
              {timer.lock ? (
                <>
                  <span>{timer.value.format(timer.format)}</span>
                  <img className={styles.lockIcon} src={lock} />
                </>
              ) : (
                '定时申报'
              )}
            </Button>
            {timer.timerComVisible ? (
              <div className={styles.timer}>
                <div className={styles.date}>{formData.date}</div>
                <TimePicker
                  popupClassName={styles.timerPopup}
                  open={true}
                  showNow={false}
                  value={timer.value}
                  format={timer.format}
                  disabledTime={() => {
                    let startTime = moment(tradeSeqInfo.submitStartTime);
                    let endTime = moment(tradeSeqInfo.submitEndTime).subtract(8, 'm');
                    let startHour = parseInt(startTime.format('HH'));
                    let endHour = parseInt(endTime.format('HH'));
                    let startMinute = parseInt(startTime.format('mm'));
                    let endMinute = parseInt(endTime.format('mm'));

                    return {
                      disabledHours: () => {
                        let res = [];
                        for (var i = 0; i <= 23; i++) {
                          if (i < startHour || i > endHour) {
                            res.push(i);
                          }
                        }
                        return res;
                      },
                      disabledMinutes: (selectedHour) => {
                        let res = [];
                        if (selectedHour === startHour) {
                          for (let i = 0; i <= 59; i++) {
                            if (i < startMinute) {
                              res.push(i);
                            }
                          }
                        }
                        if (selectedHour === endHour) {
                          for (let i = 0; i <= 59; i++) {
                            if (i > endMinute) {
                              res.push(i);
                            }
                          }
                        }
                        return res;
                      },
                    };
                  }}
                  onChange={(time) => {
                    changeTimer(true, time);
                  }}
                />
              </div>
            ) : null}
            <div className={styles.importBtn}>
              <ImportBtn
                disabled={!state.canImport}
                currentProgramId={currentProgramId + ''}
                addProgramAndSetListData={addProgramAndSetListData}
                isSd={is_SD}
              />
            </div>

            <div className={styles.exportBtn} onClick={exportProgramAsync}>
              <UploadOutlined className={styles.icon} />
              <span>导出</span>
            </div>
          </div>
        ) : null}
      </div>
      {programList.length ? (
        <ProgramSetting selectedUnitInfo={selectedUnitInfo} is_SD={is_SD} />
      ) : (
        <TRDefault type="emptysm" />
      )}
      <SubmitStatusModal ref={submitStatusRef} />
      <SearchStatusModal ref={SearchStatusRef} marketId={market.value} />
      <PriceValidationModal
        ref={priceValidationModalRef}
        priceValidationList={priceValidationList}
      />
      <PowerValidationModal
        ref={powerValidationModalRef}
        powerValidationList={powerValidationList}
      />
    </div>
  );
};

export default connect(({ global, tenDaysCentralizedBidding }) => ({
  username: global.configure.currentUser.name,
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
  initProgramInfo: tenDaysCentralizedBidding.initProgramInfo,
  tradeCenterTime: tenDaysCentralizedBidding.tradeCenterTime,
  tradeDate: tenDaysCentralizedBidding.tradeDate,
  tradeSeqId: tenDaysCentralizedBidding.tradeSeqId,
  programList: tenDaysCentralizedBidding.programList,
  currentProgramId: tenDaysCentralizedBidding.currentProgramId,
  currentProgramInfo: tenDaysCentralizedBidding.currentProgramInfo,
  unitInfo: tenDaysCentralizedBidding.unitInfo,
  hasModified: tenDaysCentralizedBidding.hasModified,
  selectedUnitIds: tenDaysCentralizedBidding.selectedUnitIds,
  tradeSeqInfo: tenDaysCentralizedBidding.tradeSeqInfo,
  stations: tenDaysCentralizedBidding.stations,
  stationCapacityInfo: tenDaysCentralizedBidding.stationCapacityInfo,
  maxValue: tenDaysCentralizedBidding.maxValue,
  formData: tenDaysCentralizedBidding.formData,
}))(Main);
